package cn.tedu.lbs.basic.web.service;

import cn.tedu.lbs.basic.web.repository.AdminRepository;
import cn.tedu.lbs.basic.web.repository.BusinessRepository;
import cn.tedu.lbs.basic.web.utils.AuthenticationContextUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminService {
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private BusinessRepository businessRepository;
    public AdminDTO adminDetail(Integer id){
        AdminPO po = adminRepository.getById(id);
        if (po!=null){
            AdminDTO dto=new AdminDTO();
            BeanUtils.copyProperties(po,dto);
            return dto;
        }else{
            return null;
        }
    }
    public AdminVO adminDetail() throws BusinessException {
        //作为过滤逻辑的下游代码 可以从同一个线程对象 获取threadLocal存储的数据
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        //添加一个严谨的 断言
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer id=userPrinciple.getId();
        //po 和 vo几乎 所有都是属性相同的,vo只会比po少属性 不会多属性
        //1.getById
        AdminPO po = adminRepository.getById(id);
        //2.转化成vo
        AdminVO vo = new AdminVO();
        BeanUtils.copyProperties(po, vo);
        return vo;
    }

    public PageResult<AdminVO> adminList(AdminQuery query) {
        //1.准备一个page对象PageResult 持久层查询 返回pageInfo
        PageResult<AdminVO> voPage=new PageResult<>(query.getPageNo(), query.getPageSize());
        //2.封装数据 返回就完成了 开启分页查询
        PageInfo<AdminPO> pageInfo= getPageInfo(query);
        //3.获取total和list 完善voPage
        voPage.setTotal(pageInfo.getTotal());
        //list需要映射 需要判断非空
        List<AdminPO> pos = pageInfo.getList();
        List<AdminVO> vos=null;
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                AdminVO vo=new AdminVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    private PageInfo<AdminPO> getPageInfo(AdminQuery query) {
        //1.利用query携带的业务条件拼接 QueryWrapper
        //2.开启分页pageHelper
        PageHelper.startPage(query.getPageNo(),query.getPageSize());
        //3.查询列表
        List<AdminPO> pos = adminRepository.list();
        //4.封装pageInfo
        return new PageInfo<>(pos);
    }

    public void adminAdd(AdminParam adminParam) throws BusinessException {
        //1.获取登录用户信息 判断业务权限 是否符合ADMIN要求
        checkRole(Roles.ADMIN);
        //2.检查入参中 该账号绑定的商家是否合法
        if (adminParam.getAccountType()==1){
            checkBusiness(adminParam.getBusinessId());
        }
        //3.幂等新增
        saveAdmin(adminParam);
    }

    private void saveAdmin(AdminParam adminParam) throws BusinessException {
        //幂等新增 逻辑 先查 后增
        //1.先查询 select count(*) from lbs_admin where account_phone=#{}
        QueryWrapper existQuery=new QueryWrapper<>();
        existQuery.eq("account_phone",adminParam.getAccountPhone());
        long count=adminRepository.count(existQuery);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号重复"));
        //2.不存在 insert
        AdminPO poParam=new AdminPO();
        BeanUtils.copyProperties(adminParam,poParam);
        poParam.setCreateTime(new Date());
        adminRepository.save(poParam);
    }

    private void checkBusiness(Integer businessId) throws BusinessException {
        //使用businessId商家id查询验证商家是否存在
        //select * from lbs_business where id=#{businessId};
        BusinessPO po = businessRepository.getById(businessId);
        Asserts.isTrue(po==null,new BusinessException("-2","商家不存在"));
    }

    private void checkRole(Roles role) throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Asserts.isTrue(userPrinciple.getRole()!=role,new BusinessException("-2","业务权限不满足"));
    }


}
